﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace Common.DataAnnotations
{
    /// <summary>
    /// 传入的值是否在枚举中已定义
    /// </summary>
    public class EnumDefinedAttribute : ValidationAttribute
    {
        private readonly Type EnumType;
        /// <summary>
        /// 传入的值是否在枚举中已定义
        /// </summary>
        /// <param name="enumType"></param>
        public EnumDefinedAttribute(Type enumType)
        {
            this.EnumType = enumType;
        }
        /// <summary>
        /// 格式化提示信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessage ?? "值[{1}]对于{0}无效", name, this.Value);
        }
        /// <summary>
        /// 输入是否合法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return true;
            }
            this.Value = value;
            return Enum.IsDefined(this.EnumType, value);
        }
        private object Value { get; set; }
    }
}
